package com.take.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.take.common.BaseContext;
import com.take.common.R;
import com.take.entity.AddressBook;
import com.take.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址簿管理
 */
@Api(tags = "地址管理模块")
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增收货地址
     */
    @ApiOperation(value = "新增收货地址")
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        log.info("addressBook:{}", addressBook);

        //如果这是当前用户保存的第一个地址，必须自动为默认
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        int addressBooksCount = addressBookService.count(lqw);
        if (addressBooksCount == 0) {
            addressBook.setIsDefault(1);   //这是用户的第一个地址，必须自动为默认
        }else{
            //新增的地址，不是用户的第一个地址
            //新增收货地址时，如果需要将当前address设置为默认(=1)，则需要取消先前的默认地址
            if (addressBook.getIsDefault() == 1) {
                //取消原来的默认地址
                LambdaUpdateWrapper<AddressBook> luw = new LambdaUpdateWrapper<>();
                luw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
                luw.eq(AddressBook::getIsDefault, 1);
                luw.set(AddressBook::getIsDefault, 0);
                addressBookService.update(luw);
            }
        }
        //保存这个地址
        addressBookService.save(addressBook);
        return R.success(addressBook);
    }

    /**
     * 设置默认地址
     */
    @ApiOperation(value = "设置默认地址")
    @PutMapping("default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
        log.info("addressBook:{}", addressBook);
        // 1.先取消其他的默认
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        wrapper.set(AddressBook::getIsDefault, 0);
        //SQL:update address_book set is_default = 0 where user_id = ?
        addressBookService.update(wrapper);
        // 2.再设置当前是默认
        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

    /**
     * 根据id查询地址
     */
    @ApiOperation(value = "根据id查询地址")
    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook != null) {
            return R.success(addressBook);
        } else {
            return R.error("没有找到该对象");
        }
    }

    /**
     * 查询默认地址
     */
    @ApiOperation(value = "查询默认地址")
    @GetMapping("default")
    public R<AddressBook> getDefault() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        queryWrapper.eq(AddressBook::getIsDefault, 1);

        //SQL:select * from address_book where user_id = ? and is_default = 1
        AddressBook addressBook = addressBookService.getOne(queryWrapper);

        return R.success(addressBook);
    }

    /**
     * 查询指定用户的全部地址
     */
    @ApiOperation(value = "查询指定用户的全部地址")
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        log.info("addressBook:{}", addressBook);

        //条件构造器
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getCreateTime);

        //SQL:select * from address_book where user_id = ? order by update_time desc
        return R.success(addressBookService.list(queryWrapper));
    }

    /**
     * 地址修改
     *
     * @return
     */
    @ApiOperation(value = "修改收货地址")
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook) {

        if (addressBook.getIsDefault() == 1) {
            //检查是否需要设置当前地址为[默认]，如果需要改默认，先取消其他的默认
            LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
            wrapper.set(AddressBook::getIsDefault, 0);
            addressBookService.update(wrapper);
        }else {
            //用户的多个地址中，【至少有一个是默认的】，如果当前地址，已经是默认地址，则不能取消默认属性
            //执行else分支，则用户要取消默认，因此先检查该地址现在是否已经为默认
            //SQL:select * from address_book where user_id = ? and is_default = 1
            LambdaQueryWrapper<AddressBook> lqwGetDefaultAddress = new LambdaQueryWrapper<>();
            lqwGetDefaultAddress.eq(AddressBook::getUserId, BaseContext.getCurrentId());
            lqwGetDefaultAddress.eq(AddressBook::getIsDefault, 1);
            AddressBook defaultAddressBook = addressBookService.getOne(lqwGetDefaultAddress);
            if(defaultAddressBook==null || defaultAddressBook.getId().equals(addressBook.getId())){
                //判断出，当前的addressBook是唯一默认，因此不让取消掉默认属性
                addressBook.setIsDefault(1);
            }
        }

        //更新地址（包含默认信息）
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }

    @ApiOperation(value = "删除收货地址")
    @DeleteMapping
    public R<String> delete(@RequestParam List ids) {
        log.info("将删除AddressBook Id--->{}", ids);
        addressBookService.removeByIds(ids);
        return R.success("删除成功");
    }


}
